#ifndef CONNECTION_H
#define CONNECTION_H

#include <QHostAddress>
#include <QString>
#include <QImage>
#include <QTcpSocket>
#include <QTime>
#include <QTimer>

static const int MaxBufferSize = 1024000;

class Connection : public QTcpSocket
{
    Q_OBJECT

public:
    enum ConnectionState            ///  连接状态
    {
        WaitingForGreeting,         ///< 等待对等客户端欢迎消息
        ReadingGreeting,            ///< 正在读取欢迎消息
        ReadyForUse                 ///< 空闲
    };
    enum DataType                   ///  数据类型
    {
        Message,                    ///< 泛型消息
        Ping,                       ///< Ping探测
        Pong,                       ///< Pong探测回复
        Greeting,                   ///< 欢迎消息
        Undefined                   ///< 未定义消息
    };
    enum DataScope
    {
        Public = 1000,              ///< 公有消息域
        Private,                    ///< 私有消息域
        Unknown                     ///< 未知消息域
    };

    Connection(QObject *parent = 0);

    QString name() const;
    void setGreetingMessage(const QString &message);
    bool sendMessage(Connection::DataScope scope, const QVariant &message);

signals:
    void readyForUse();
    void newMessage(Connection::DataScope scope, const QString &from, const QVariant &message);

protected:
    void timerEvent(QTimerEvent *timerEvent);

private slots:
    void processReadyRead();
    void sendPing();
    void sendGreetingMessage();

private:
    int readDataIntoBuffer(int maxSize = MaxBufferSize);
    int dataLengthForCurrentDataType();
    bool readProtocolHeader();
    bool hasEnoughData();
    void processData();

    QString greetingMessage;
    QString username;
    QTimer pingTimer;               ///< 周期Ping触发器
    QTime pongTime;                 ///< Pong计时器
    QByteArray buffer;              ///< 缓冲区
    ConnectionState state;          ///< 连接状态
    DataType currentDataType;       ///< 数据包类型
    DataScope currentDataScope;     ///< 数据包域
    int numBytesForCurrentDataType;
    int transferTimerId;
    bool isGreetingMessageSent;
};

#endif
